<?php
namespace app\single\controller;
use think\validate;
class Task extends Common{
    /**
     * 获取任务菜单列表
     * @return json
     */
    function navs(){
        $navs=model('taskgroup')->readAll(['status'=>1,'phone'=>1],0,['with'=>'taskoptionsphone']);
        $prefix=request()->domain().'/taskicon/';
        $suffix='.png';
        foreach ($navs as $key => $v) {
            foreach ($v['taskoptionsphone'] as $k => $c) {
                $c['icon']=$prefix.$c['icon'].$suffix;
                if(is_string($c['params'])){
                    $c['params']=json_decode($c['params'],true);
                }
            }
            $navs[$key]['children']=$v['taskoptionsphone'];
        }
        return json(['data'=>$navs]);
    }
 

    /**
     * 获取任务列表
     * @param  integer $page 页数
     * @param  integer $tag 标签 1简单2高额3人气
     * @return [type]      [description]
     */
    function getTaskList(){
        $this->ergodicTask();
        $uid = $this->user->toArray()['id'];
        $page=input('page/d',1);
        $size = 20;
        $start = ($page-1)*$size;

        $time = time();
        $params=[];
        $params['starttime'] = ['starttime','lt',$time];
        $params['endtime'] = ['endtime','gt',$time];

        $tag = input('tag/d');
        if(!empty($tag)){
            $where = 'FIND_IN_SET('.$tag.', tag)';
        }else{
            $where = 1;
        }

        // 标题，类型，标签，状态，奖励，已完成数，开始时间
        $field='id,title,type,tag,status,reward,fquantity,starttime';
        $list= model('release_task')->field($field)->where($params)->where($where)->paginate($start,$size);

        $data = $list->toArray()['data'];
        foreach ($data as &$value) {
            // 查找用户任务ID
            $mTask = model('member_task')->where(['uid'=>$uid,'tid'=>$value['id']])->where('status','in','1,2')->order('id desc')->find();
            $value['mtid'] = 0;
            if(!empty($mTask)){
                $value['mtid'] = $mTask['id'];
            }
            // 是否是简单
            $tagArr = explode(',', $value['tag']);
            $value['is_simple'] = in_array(1, $tagArr)?1:0;
            // 是否是高额
            $value['is_high'] = in_array(2, $tagArr)?1:0;
            // 是否是人气
            $value['is_popularity'] = in_array(3, $tagArr)?1:0;
        }
        // print_r($data);die;

        // echo json_encode($data);die;
        return json("",0,$data);die;
    }

    /**
     * 获取任务详情
     * @param  integer $id 任务ID
     * @param  integer $rid 用户任务ID
     * @return [type]      [description]
     */
    function getTaskDetails(){
        $this->ergodicTask();
        $uid = $this->user->toArray()['id'];
        $id=input('id/d',0);
        if(!$id){
            return json("非法操作",1);die;
        }
        $params=['id'=>$id];
        
        // 标题，类型，标签，状态，用户可做次数，奖励，任务说明，实例图片，任务步骤，超时时间，共可做任务次数，提交次数，审核通过数，开始时间,截止时间
        $field='title,type,tag,status,limit,reward,illustrate,image_group,step,overtime,number,squantity,fquantity,starttime,endtime';
        $data = model('release_task')->field($field)->where($params)->find();
        if(empty($data)){
            return json("不存在该任务",2);die;
        }
        if($data['status']==1&&$data['endtime']<=time()){ // 过期下架
            $e=model('release_task')->edit(['id'=>$id,'status'=>0]);
            if($e){
                $data['status']=0;
            }
        }
        $data = $data->toArray();
        // 是否是简单
        $tagArr = explode(',', $data['tag']);
        $data['is_simple'] = in_array(1, $tagArr)?1:0;
        // 是否是高额
        $data['is_high'] = in_array(2, $tagArr)?1:0;
        // 是否是人气
        $data['is_popularity'] = in_array(3, $tagArr)?1:0;
        
        // 解析图片组与任务步骤
        $data['image_group'] = json_decode($data['image_group'],true);
        if(!empty($data['image_group'])){
            foreach ($data['image_group'] as &$value) {
                $value = images($value);
            }
        }
        
        $data['TaskStep'] = json_decode($data['step'],true);
        foreach ($data['TaskStep'] as &$value) {
            if(!empty($value['image_group'])){
                foreach ($value['image_group'] as &$v) {
                    $v = images($v);
                }
            }
        }
        unset($data['step']);

        // 通过率计算 审核通过数/用提交数
        if($data['fquantity']>0 && $data['squantity']>0){
            $data['chance'] = $data['fquantity'] / $data['squantity'] * 100;
            $data['chance'] = round($data['chance']);
        }else{
            $data['chance'] = 0;
        }

        // 赏金猎人
        $memberlist = model('member_task')->alias('t')->field("m.head_img,m.name,t.examinetime time")->join("member m","t.uid = m.id")->where(['t.tid'=>$id,'t.status'=>3])->order('t.id desc')->select()->toArray();
        foreach ($memberlist as &$value) {
            $value['head_img'] = $_SERVER['SERVER_NAME']."/uploads".$value['head_img'];
        }
        $data['BountyHunterData'] = $memberlist;
        
        // 当前用户完成次数  领取时间  超时时间  状态
        $mtid=input('mtid/d',0);
        $data['complete'] = model('member_task')->where(['uid'=>$uid,'tid'=>$id,'status'=>3])->count();
        if($mtid>0){
            $member_task = model('member_task')->where(['id'=>$mtid])->find();
            // 如果是过期任务
            if($member_task['status']==-2){
                $member_task = model('member_task')->where(['uid'=>$uid,'tid'=>$id])->where('status','in','1,2')->find();
            }
        }else{
            $member_task = model('member_task')->where(['uid'=>$uid,'tid'=>$id])->where('status','in','1,2')->find();
        }

        if(empty($member_task)){
            $data['accepttime'] = 0;
            $data['termtime'] = 0;
            $data['member_status'] = 0;
            $data['StepSaveData'] = [
                'linkEd'=>0,
                'images'=>[],
                'text'=> ''
            ];
        }else{
            $data['accepttime'] = $member_task['creattime'];
            $data['termtime'] = $member_task['creattime'] + 7200;
            $data['member_status'] = $member_task['status'];

            if(!empty($member_task['submission'])){
                $data['StepSaveData'] = json_decode($member_task['submission'],true);
            }else{
                $data['StepSaveData'] = [
                    'linkEd'=>0,
                    'images'=>[],
                    'text'=> ''
                ];
            }
        }
        

        /**
            title         标题
            type          类型 1金钱 2微豆
            tag           标签
            status        状态 1上架0下架
            limit         用户可做次数 
            reward        奖励 多少钱/微豆
            illustrate    任务说明
            image_group   实例图片
            TaskStep      任务步骤
            overtime      超时时间
            number        共可做任务次数
            squantity     提交次数
            fquantity     审核通过数
            chance        通过率
            starttime     开始时间
            endtime       截止时间
            is_simple     是否是简单
            is_high       是否是高额
            is_popularity 是否是人气
            complete      完成次数
            accepttime    用户接受时间
            termtime      任务期限
            member_status 用户完成状态
        */
        // print_r($data);die;
        // echo json_encode($data);die;
        return json("",0,$data);die;

    }

    /**
     * 接取任务
     * @param  integer $tid 任务ID
     * @return [type]      [description]
     */
    function AcceptTask(){
        $uid = $this->user->toArray()['id'];
        $tid = input('id/d',0)?input('id/d',0):input('tid/d',0);
        if(!$tid){
            return json("非法操作",1);die;
        }
        
        $task = model('release_task')->where(['id'=>$tid])->find();
        if(empty($task)){
            return json("此任务不存在",2);die;
        }

        // 判断用户是否做过该任务
        $member_task = model('member_task')->where(['uid'=>$uid,'tid'=>$tid])->where('status','in','1,2,3')->count();
        if($task['limit']<=$member_task){
            return json("该任务已接受或已完成",3);die;
        }

        $data = [
            'uid'=> $uid,
            'uname'=> $this->user->toArray()['name'],
            'tid'=> $tid,
            'title'=> $task['title'],
            'type'=> $task['type'],
            'reward'=> $task['reward'],
            'eovertime'=>time()+$task['overtime']*3600,
            'creattime'=>time()
        ];
        
        $result = model('member_task')->insert($data);
        if($result){
            model('release_task')->where(['id'=>$tid])->setInc('aquantity');
        }
        return json("接受任务成功",0);die;
    }


    /**
     * 提交任务审核
     * @param  integer $tid 用户任务ID
     * @return [type]      [description]
     */
    function SubmitTask(){
        $uid = $this->user->toArray()['id'];
        $tid = input('tid/d',0);
        if(!$tid){
            return json("非法操作",1);die;
        }
        
        $task = model('release_task')->where(['id'=>$tid])->find();
        if(empty($task)){
            return json("此任务不存在",1);die;
        }

        $where = ['tid'=>$tid,'uid'=>$uid,'status'=>1];
        $result = model('member_task')->where($where)->update(['status'=>2,'submittime'=>time()]);
        if($result){
            model('release_task')->where(['id'=>$tid])->setInc('squantity');
        }
        return json("提交审核成功",0);die;
    }   

    /**
     * 提交任务资料
     * @param  integer $tid 任务ID
     * @param  string $linkEd 数字 1点击
     * @param  string $text 文本
     * @param  json $images 图片
     * @return [type]      [description]
     */
    function DataSubmitting(){
        $uid = $this->user->toArray()['id'];
        $tid = input('tid/d',0);
        if(!$tid){
            return json("非法操作",1);die;
        }

        $where = ['tid'=>$tid,'uid'=>$uid,'status'=>1];
        $data = model('member_task')->where($where)->find();

        if(empty($data)){
            $data = [
                'linkEd'=>0,
                'images'=>[],
                'text'=> ''
            ];
        }else{
            $data = $data['submission'];
            $data = json_decode($data,true);
        }

        // 点击链接
        $linkEd = input('linkEd/d');
        // 图片
        $images = input('images');
        // 文本
        $text = input('text/s');
        
        if(!empty($linkEd)){
            $data['linkEd'] = $linkEd;
        }
        if(!empty($images)){
            if(!empty($images)){
                $images = json_decode($images,true);
            }
            $data['images'] = $images;
        }
        if(!empty($text)){
            $data['text'] = $text;
        }

        model('member_task')->where($where)->update(['submission'=>json_encode($data)]);
        return json("提交任务资料成功",0);die;
    }

    /**
     * 用户任务列表
     * @param  integer $status 状态
     * @param  integer $page 页数
     * @return [type]      [description]
     */
    function memberTaskList(){
        $this->ergodicTask();
        $uid = $this->user->toArray()['id'];
        $status = input('status/d',0);

        $page=input('page/d',1);
        $size = 20;
        $start = ($page-1)*$size;

        if(!$uid){
            return json("非法操作",1);die;
        }

        $where = ['t.uid'=>$uid];
        if($status>0){
            $where['t.status'] = $status;
        }

        $list= model('member_task')->alias('t')->field("r.id,t.id mtid,r.title,r.type,t.status,r.reward,t.reason,t.creattime")->join("release_task r","t.tid = r.id")->where($where)->paginate($start,$size);
        foreach ($list as &$value) {
            $value['overtime'] = $value['creattime'] + 7200;
        }

        
        return json("",0,$list->toArray()['data']);die;
    }

    /**
     * 任务列表附加数据
     * @param  integer $uid 状态
     * @return [type]      [description]
     */
    function AdditionalData(){
        $uid = $this->user->toArray()['id'];
        if(!$uid){
            return json("非法操作",1);die;
        }

        $data = [
            // 累计收入
            'count_income' => 0,
            // 累计奖励
            'count_reward' => 0,
            // 我的任务
            'count_task' => 0,
            // 今日任务个数
            'today_task' => 0,
            // 今日任务奖励金额
            'today_income' => 0,
            // 今日任务奖励微豆
            'today_reward' => 0
        ];
        // 今日
        $time = time();
        $params=[];
        $params['starttime'] = ['starttime','lt',$time];
        $params['endtime'] = ['endtime','gt',$time];

        $field='type,status,reward';
        $list= model('release_task')->field($field)->where($params)->select();
        foreach ($list as &$value) {
            if($value['type']==1){
                // 累计收入
                $data['today_income'] += $value['reward'];
            }else{
                // 累计奖励
                $data['today_reward'] += $value['reward'];
           }
        }
        // 今日任务
        $data['today_task'] = count($list->toArray());



        // 累计
        $where = ['t.uid'=>$uid];
        $list= model('member_task')->alias('t')->field("r.type,t.status,r.reward")->join("release_task r","t.tid = r.id")->where($where)->select();
        
        foreach ($list as &$value) {
            if($value['status']==3){
                if($value['type']==1){
                    // 累计收入
                    $data['count_income'] += $value['reward'];
                }else{
                    // 累计奖励
                    $data['count_reward'] += $value['reward'];
               }
            }
        }
        // 我的任务
        $data['count_task'] = count($list->toArray());

        return json("",0,$data);die;
    }

    /**
     * 任务图片上传接口
     * @param   Obj          $file 状态
     * @return [type]      [description]
     */
    function uploadsImages(){
        $file=request()->file('file');

        if(!empty($file)){
            $fileArr = [];
            foreach ($file as &$value) {
                $fileArr[] = $value;
            }

            $data = [];
            foreach ($fileArr as $file) {
                $res=$this->loadHeadImg($file);
                if(!$res['success']){
                    return json($res['msg'],1);
                }
                // if($image){
                //     $this->deleteUploadFile($image);
                // }
                $data[] = $res['msg'];
            }

            return json('',0,$data);
        }
    }

    function ergodicTask(){
        // 任务超时时间
        $overtime = time()-7200;
        model('member_task')->where('creattime','lt',$overtime)->where('status','in','1')->update(['status'=>-2]);
        // foreach ($data as $key => $value) {
        //     model('member_task')->where(['id'=>$value['id']])->update(['status'=>-2]);
        // }

        // 超过审核时间
        $data = model('member_task')->alias('t')->join("release_task r","t.tid = r.id")->field('t.id,r.type,r.reward')->where('t.eovertime','lt',time())->where('t.status','in','2')->select()->toArray();

        foreach ($data as $key => $value) {
            $result = model('member_task')->where(['id'=>$value['id']])->update(['status'=>3,'is_eovertime'=>1]);

            if($result){
                if($value['type']==2){
                    // 给微豆
                    model('member')->where(['id'=>$value['uid']])->setInc('coin',$value['reward']);
                }else if($value['type']==1){
                    // 给金额
                    model('member')->where(['id'=>$value['uid']])->setInc('money',$value['reward']);
                }
            }
        }

    }

    function mb_unserialize($str) {
        return preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';},$str);
    }

}